package cn.aihongbo.kmp.base.widget

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import cn.aihongbo.kmp.pages.HomePage
import cn.aihongbo.kmp.pages.MessagePage
import cn.aihongbo.kmp.pages.MyPage
import cn.aihongbo.kmp.pages.OrderPage
import cn.aihongbo.kmp.pages.WorkPage
import kotlinx.coroutines.launch

@Composable
fun MainScreen() {
    var currentDestination by rememberSaveable {
        mutableStateOf("tab_home")
    }
    val pagerState = rememberPagerState { 5 }
    val scope = rememberCoroutineScope()

    LaunchedEffect(pagerState) {
        snapshotFlow { pagerState.currentPage }.collect { page ->
            currentDestination = HNavigation.entries[page].route
        }
    }
    Column(modifier = Modifier.fillMaxSize().background(Color.White)) {
        HorizontalPager(
            state = pagerState,
            userScrollEnabled = true,
            modifier = Modifier.fillMaxWidth().weight(1.0f)
        ) { page ->
            when (page) {
                0 -> HomePage()
                1 -> MessagePage()
                2 -> OrderPage()
                3 -> WorkPage()
                4 -> MyPage()
            }
        }
        HTabBar(
            destinations = HNavigation.entries,
            currentDestination = currentDestination,
            onNavigationTo = { index ->
                currentDestination = HNavigation.entries[index].route
                scope.launch {
                    pagerState.animateScrollToPage(index)
                }
            },
        )
    }
}